﻿using System;
using System.Collections.Generic;
using System.Linq;
using Spring.Context.Support;
using Spring.Aspects.Cache;
using Spring.Caching;
using Spring.Aop.Framework;

namespace Macds.WebService
{
    public abstract class CacheServiceBase
    {
        private static GenericApplicationContext context;
        private static CacheAspect cacheAspect;
        private static Dictionary<string, object> services;

        public CacheServiceBase(string cacheName)
        {
            if (context == null)
            {
                services = new Dictionary<string, object>();
                context = new GenericApplicationContext();
                cacheAspect = new CacheAspect();
                cacheAspect.ApplicationContext = context;
                log4net.Config.XmlConfigurator.Configure();

                if (!context.ObjectFactory.SingletonNames.Contains(cacheName))
                {
                    ICache cache = new AspNetCache();
                    context.ObjectFactory.RegisterSingleton(cacheName, cache);
                }
            }
        }

        protected T GetService<T>(Type classType)
        {
            if(!services.Keys.Contains(classType.Name.Trim()))
            {
                ProxyFactory pf = new ProxyFactory(Activator.CreateInstance(classType));
                pf.AddAdvisors(cacheAspect);
                T service = (T)pf.GetProxy();
                services.Add(classType.Name.Trim(), service);
            }

            return (T)services[classType.Name.Trim()];
        }
    }
}
